package com.itheima.homework;

import com.itheima.dao.StudentMapper;
import com.itheima.bean.Student;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

@WebServlet("/RequestServlet2")
public class StudentRegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码
        req.setCharacterEncoding("UTF-8");
        //设置网页请求行的编码
        resp.setContentType("text/html; charset=UTF-8");
        //获取用户输入的信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobby");
        String s = Arrays.toString(hobbies);
        //使用mybatis查询用户名是否存在
        SqlSession autoCommitSession = MybatisUtil.getAutoCommitSession();
        StudentMapper mapper = autoCommitSession.getMapper(StudentMapper.class);
        Student student = mapper.selectByStudentName(username);
        PrintWriter writer = resp.getWriter();
        if(student != null){
            //用户名存在注册失败
            writer.println("<script>");
            writer.println("alert('用户名已存在,注册失败')");
            //跳转回注册页面
            writer.println("location.href='student-regist.html'");
            writer.println("</script>");
        }else {
            //用户名不存在注册成功  将用户输入的信息存到数据库
            student = new Student(null,username,password,s);
            mapper.addStudent(student);
            writer.println("<script>");
            writer.println("alert('注册成功')");
            //跳转到登录页面
            writer.println("location.href='login.html'");
            writer.println("</script>");
        }
        autoCommitSession.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
